package org.popupcommunication.service.impl;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.popupcommunication.dao.GroupDAO;
import org.popupcommunication.dao.UserDAO;
import org.popupcommunication.model.Agenda;
import org.popupcommunication.model.AgendaGroupe;
import org.popupcommunication.model.Group;
import org.popupcommunication.model.User;
import org.popupcommunication.service.AgendaGroupeManager;
import org.popupcommunication.service.UserManager;
import org.popupcommunication.web.UserFormAdmin;
import org.popupcommunication.web.UserFormRegister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;

@Transactional
public class UserManagerBean  implements UserManager{

	private  UserDAO userRepository;	
	@Autowired GroupDAO groupRepository;
	private AgendaGroupeManager agendaGroupeService;

	public AgendaGroupeManager getAgendaGroupeService() {
		return agendaGroupeService;
	}

	public void setAgendaGroupeService(AgendaGroupeManager agendaGroupeService) {
		this.agendaGroupeService = agendaGroupeService;
	}

	public UserDAO getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserDAO userRepository) {
		this.userRepository = userRepository;
	}

	public List<Agenda> getEventsGroup(User toto){
		List<Agenda> listEvents = new ArrayList<Agenda>();
		for(Group gr : toto.getListGroup()){
			if (gr != null){
			listEvents.addAll(agendaGroupeService.getEventByGroup(gr));
			//System.out.println("nb event:" +listEvents.size());
			}
		}
		return listEvents;		
	}
	
	@Override
	public boolean checkUserExists(String email, String pwd) {
		User user = userRepository.findByEmail(email);

		if (user != null && user.getPassword().equals(pwd)) {
			return true;
		}
		return false;
	}
	
	private  User toUser(UserFormAdmin f){
		User u = new User();
		u.setFirstName(f.getFirstName());
		u.setLastName(f.getLastName());
		u.setEmail(f.getEmail());
		u.setPassword(f.getPassword());
		u.setAdmin(f.getIsAdmin());
		u.setFonction(f.getFonction());
		u.setGsm(f.getGsm());
		u.setTel(f.getTel());
		u.setInstitution(f.getInstitution());
		if (f.getListGroup() !=null){
			for(Group g : f.getListGroup()){				
				g = groupRepository.merge(g);
				u.addGroup(g);
				g.addUser(u);
			}	
		}
		return u;	
	}
	
	private String encodeSha(String password ) throws NoSuchAlgorithmException{
		MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(password.getBytes());        
        byte byteData[] = md.digest(); 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
		return sb.toString();
	}
	
	private  User toUser(UserFormRegister f) {
		User u = new User();
		//crypter password
		String pwd=null;
		try {
			pwd = encodeSha(f.getPassword());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		u.setFirstName(f.getFirstName());
		u.setLastName(f.getLastName());
		u.setEmail(f.getEmail());
		u.setPassword(pwd);
		u.setAdmin(false);
		u.setActivate(false);
		u.setListGroup(null);
		u.setDateLastBadAttempt(null);
		u.setErrorConnection(0);
		u.setDateReactivate(null);
		u.setSrcAvatar(f.getAvatar());
		u.setCodeVerif(null);
		u.setDateLimitCode(null);
		u.setDateLastConnexion(null);
		u.setDateRegister(new Date());
		u.setFonction(f.getFonction());
		u.setGsm(f.getGsm());
		u.setTel(f.getTel());
		u.setInstitution(f.getInstitution());
		return u;	
	}	

	@Override   
    public boolean registerUser(UserFormAdmin f, String email, String password, Errors errors) {
        //TODO: crypter mot de passe
        //http://www.jasypt.org/encrypting-passwords.html
        //http://www.mkyong.com/spring-security/spring-security-password-hashing-example/
       // u.setPwd(SecurityUtils.md5Encode(password));
        if (userRepository.findByEmail( f.getEmail()) != null)    {
        	errors.rejectValue("email", "user.exist", new String[]{ f.getEmail()}, null);
        }		
        boolean valid = !errors.hasErrors();
        if (valid){
        	userRepository.add(toUser(f));     	
        }
        return valid;
    }
	@Override
	public User findByEmail(String email){
		return userRepository.findByEmail(email);
	}
	@Override
	public void updateUser(User userToUpdate){
		userRepository.updateUser(userToUpdate);
	}

	@Override
	public List<User> getUsers() {
		return userRepository.getUsers();
	}

	@Override
	public boolean register(UserFormRegister f, Errors errors) {
        if (userRepository.findByEmail( f.getEmail()) != null)    {
        	errors.rejectValue("email", "user.exist", new String[]{ f.getEmail()}, null);
        }
        boolean valid = !errors.hasErrors();
        if (valid){
        	userRepository.add(toUser(f));     	
        }      
		return valid;
	}

	@Override
	public List<User> getUsersWaintingValidation() {
		List<User> lst = userRepository.getUsersWaitingValidation();
		return lst;
	}

	@Override
	public List<User> getAdmins() {
		return userRepository.getAdmins();
	}

	@Override
	public List<Agenda> getCurrentsEventsUsers(User u) {
		return userRepository.getCurrentsEventsUsers(u);
	}

	@Override
	public List<Agenda> getCurrentsEventsPersoUsers(User u) {
		return userRepository.getCurrentsEventsPersoUsers(u);
	}



}
